﻿using AutoMapper;
using BW.MesProject.Public.Application.Dto.Input;
using BW.MesProject.Public.Application.Dto.Output.DocCode;
using BW.MesProject.Public.Domain.Model;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BW.MesProject.Public.Application.DocCode
{
    public class DocServices : IDocServices
    {
        private readonly IBaseRepository<DOCCODEMODEL> _docCodeRepository;
        private readonly IMapper _mapper;
        public DocServices(IBaseRepository<DOCCODEMODEL> docCodeRepository, IMapper mapper)
        {
            _docCodeRepository = docCodeRepository;
            _mapper = mapper;
        }

        public ApiResult<int> CreateDocCode(DocInput input)
        {
            DOCCODEMODEL docCode = _mapper.Map<DOCCODEMODEL>(input);
            docCode.CREATEDTIME = DateTime.Now;
            docCode.CREATEDBY = "admin"; // 可以根据实际情况设置创建人
            int r = _docCodeRepository.Add(docCode);
            if (r > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Message = "文档编码创建成功",
                    Data = r
                };
            }
            else
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Error,
                    Message = "文档编码创建失败",
                    Data = r
                };
            }
        }

        public ApiResult<List<DocCodeOutput>> GetDocCodeList()
        {
            ISugarQueryable<DOCCODEMODEL> query = _docCodeRepository.GetAll()
                .Where(x => !x.ISDELETED)
                .OrderBy(x => x.CREATEDTIME, OrderByType.Desc);
            List<DocCodeOutput> list = _mapper.Map<List<DocCodeOutput>>(query.ToList());
            if (list.Count > 0)
            {
                return new ApiResult<List<DocCodeOutput>>
                {
                    Code = ApiEnums.Success,
                    Message = "文档编码列表获取成功",
                    Data = list
                };
            }
            else
            {
                return new ApiResult<List<DocCodeOutput>>
                {
                    Code = ApiEnums.Error,
                    Message = "文档编码列表为空",
                    Data = null
                };
            }
        }
    }
}